//
//  FZEmotionToolBar.swift
//  MyWeiBo
//
//  Created by fangzhengwei on 2017/4/6.
//  Copyright © 2017年 fangzhengwei. All rights reserved.
//

import UIKit

enum emotionType : Int{
    case recent = 10
    case defaut = 20
    case emoji = 30
    case flower = 40
}
class FZEmotionToolBar: UIStackView {
    
    var emotionClosure : ((emotionType)->())?
    
    fileprivate var lastSelectedBtn : UIButton?
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        setupUI()
    }
    
    func setupUI() {
        
        self.axis = .horizontal
        self.distribution = .fillEqually
        loadBtns(imageName: "compose_emotion_table_left", title: "最近", buttonType: .recent)
        loadBtns(imageName: "compose_emotion_table_mid", title: "默认", buttonType: .defaut)
        loadBtns(imageName: "compose_emotion_table_mid", title: "Emoji", buttonType: .emoji)
        loadBtns(imageName: "compose_emotion_table_right", title: "浪小花", buttonType: .flower)
    }
    
    fileprivate func loadBtns(imageName : String ,title : String, buttonType : emotionType) {
        let btn = UIButton()
        btn.tag = buttonType.rawValue
        btn.setBackgroundImage(UIImage(named : "\(imageName)_normal"), for: .normal)
        btn.setBackgroundImage(UIImage(named : "\(imageName)_selected"), for: .selected)
        btn.setTitle(title, for: .normal)
        btn.setTitleColor(UIColor.white, for: .normal)
        btn.setTitleColor(UIColor.darkGray, for: .selected)
        btn.addTarget(self, action: #selector(clickEmotionComposeButton(btn:)), for: .touchUpInside)
        btn.adjustsImageWhenHighlighted = false
        btn.sizeToFit()
        addArrangedSubview(btn)
        
        //默认选中
        if buttonType == .defaut {
            
           lastSelectedBtn?.isSelected = false
           btn.isSelected = true
           lastSelectedBtn = btn
        }
    }
    
    @objc fileprivate func clickEmotionComposeButton(btn : UIButton) {
               //取消上一次选中,这一次选中
        if lastSelectedBtn == btn {
            return
        }
        lastSelectedBtn?.isSelected = false
        
        btn.isSelected = true
        
        lastSelectedBtn = btn
        let buttonType = emotionType(rawValue: btn.tag)
        //闭包回调点击按钮的枚举类型
        if let type = buttonType {
            emotionClosure?(type)
        }

    }

    required init(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

extension FZEmotionToolBar {
    
    func scrollToSelctedButton(section : Int) {
        
       let btn = viewWithTag((section + 1) * 10) as! UIButton
        
        if lastSelectedBtn == btn {
            return
        }
        
        lastSelectedBtn?.isSelected = false
        
        btn.isSelected = true
        
        lastSelectedBtn = btn
        
    }
    
    
}


